﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DPS.Prototype.Model;

namespace DPS.Prototype.PolicyBase.Filters.WorkOrderFilters
{
    public class HoldingModelsFilter : WorkOrderFiltersBase
    {
        private static List<HoldingModels> holdingModelsCache=new List<HoldingModels>();
        private static bool _isInitializeCache = false;
        private static object lockObj = new object();

        protected override List<Model.WorkOrder> FilterProcess(List<Model.WorkOrder> matchedOrders, ProdCompetitorBase prodCompetitor)
        {
            HoldingModelsFilter.EnsureInitializeCache();
            List<Model.WorkOrder> models = new List<WorkOrder>();
            matchedOrders.ForEach(m => {
                if (CheckModelInHolding(m.Model, prodCompetitor.LastProducedCapacity.StartTime))
                {
                    models.Add(m);
                }
            });
            return models;
        }

        private bool CheckModelInHolding(string modelName,DateTime currentProduceTime)
        {
            HoldingModelsFilter.EnsureInitializeCache();
            var query = holdingModelsCache.Where(m => m.Model == modelName&&(currentProduceTime<=m.EndTime&&currentProduceTime>=m.BeginTime));
            return query.Count() > 0;
        }

        private static void EnsureInitializeCache()
        {
            if (!_isInitializeCache)
            {
                lock (lockObj)
                {
                    if (!_isInitializeCache)
                    {
                        holdingModelsCache = Factory.HoldingModelsProviderFactory.CreateHoldingModelsProvider().GetAllHoldingModels();
                    }
                }
            }
        }

         

    }
}
